import datetime
from typing import List, Dict

from sqlalchemy import Boolean, Column, DateTime, Integer, String, Index, text, ForeignKey, JSON, TEXT, and_
from sqlalchemy.orm import Session, relationship
from sqlalchemy.orm import Session

from common.database import Base
from common.database import SessionMixin


class MonitorDorisExclude(Base, SessionMixin):
    __tablename__ = 'monitor_doris_exclude'
    service_name = Column(String(128), nullable=False, comment="策略名称")  # 策略名称等于应用名称
    username = Column(String(128), nullable=False, comment="申请人")
    exclude = Column(TEXT, nullable=False, comment="排除关键字")
    is_active = Column(Boolean, default=text('true'), nullable=False, comment="屏蔽状态")
    effective_datetime = Column(DateTime, nullable=False, comment="生效时间")
    expiration_datetime = Column(DateTime, nullable=False, comment="失效时间")
    comment = Column(String(255), nullable=True, comment="屏蔽说明")
    create_time = Column(DateTime, default=datetime.datetime.now, nullable=False, comment="创建时间")
    update_time = Column(DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now, nullable=False, comment="更新时间")

    __table_args__ = (
        Index('idx_monitor_doris_exclude_uuid', 'uuid', unique=True),
        {
            'mysql_engine': 'innodb',
            'mysql_charset': 'utf8mb4',
            'mysql_collate': 'utf8mb4_unicode_ci',
            'extend_existing': True,
            'mysql_row_format': 'dynamic',
        }
    )

    def __repr__(self):
        return "<uuid='{}',service_name='{}',exclude='{}'>".format(self.uuid, self.service_name, self.exclude)

    @classmethod
    def get_exclude_by_service_name(cls, db: Session, service_name) -> List:
        exclude_infos = db.query(cls).filter(
            cls.service_name == service_name
        ).to_dict()
        return exclude_infos

    @classmethod
    def get_effective_excludes(cls, db: Session, service_name: str, date_time: str) -> List:
        # 获取时间有效的屏蔽关键字
        exclude_infos = db.query(cls).with_entities(cls.exclude).filter(
            cls.service_name == service_name,
            cls.expiration_datetime > date_time
        ).to_dict()
        return exclude_infos
